<template>

  <div id="Company_medcode_search">
    <span>
      <img src="../assets/trace.png" alt="" class="bread-icon">
    </span>
    <el-breadcrumb style="display:inline-block">
      <el-breadcrumb-item>
        <span style="font-size:20px;">追溯码管理</span>
      </el-breadcrumb-item>
      <el-breadcrumb-item>
        <span style="font-size:15px;line-height:20px;">追溯码查询</span>
      </el-breadcrumb-item>
    </el-breadcrumb>
    <div class="content-wrap">
      <div class="topNav">
        <span class="navLeft">基本信息查询</span>
        <span class="navRight">
          <el-button size="small" @click="traceSearch" class="searchInput" icon="el-icon-search">搜索</el-button>
          <el-button size="small" @click="setColumns" class="el-button--primary" icon="el-icon-setting">设置</el-button>
        </span>
        <span class="navMid">
          <el-input v-model="searchData" size="small" placeholder="请输入追溯码ID"></el-input>
        </span>
      </div>
      <el-table :data="traceData.data" v-loading="traceData.loading" class="table-common" :max-height="tableHeight" border>
        <el-table-column prop="cur_code" label="追溯码" v-if='columns.contains("追溯码")'>
        </el-table-column>
        <el-table-column label="生产日期" v-if='columns.contains("生产日期")'>
          <template slot-scope="scope">
            {{scope.row.batch.made_date |dateFormat}}
          </template>
        </el-table-column>
        <el-table-column prop="drug.common_name" label="药品通用名称" v-if='columns.contains("药品通用名称")'>
        </el-table-column>
        <el-table-column prop="drug.approval_number" label="批准文号" v-if='columns.contains("批准文号")'>
        </el-table-column>
        <el-table-column prop="drug.approval_expiry_date" label="批准文号有效期" v-if='columns.contains("批准文号有效期")'>
        </el-table-column>
        <el-table-column prop="drug.expiry_date_number" label="药品有效期" v-if='columns.contains("药品有效期")'>
        </el-table-column>
        <el-table-column prop="drug.expiry_date_unit" label="有效期单位" v-if='columns.contains("有效期单位")'>
        </el-table-column>
        <el-table-column prop="drug.standard" label="制剂规格" v-if='columns.contains("制剂规格")'>
        </el-table-column>
        <el-table-column prop="drug.factory" label="生产企业" v-if='columns.contains("生产企业")'>
        </el-table-column>
        <!-- <el-table-column prop="drug.enterprise" label="所属企业" v-if='columns.contains("所属企业")'>
        </el-table-column> -->
        <el-table-column label="操作" width="292">
          <template slot-scope="scope">
            <el-button @click="showForm(scope.row)" type="info" plain size="mini">查看详情</el-button>
            <el-button @click="showLocation(scope.row)" type="primary" plain size="mini">位置信息</el-button>
            <el-button @click="showLink(scope.row)" type="primary" size="mini">关联关系</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="block" style="text-align:center">
        <el-pagination @size-change="traceHandleSizeChange" @current-change="traceHandleCurrentChange" :current-page="traceData.currentPage"
          :page-sizes="[20]" :page-size="traceData.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="traceData.dataSize">
        </el-pagination>
      </div>
    </div>
    <el-dialog title="追溯码详情" :visible.sync="dialogFormVisibleShow">
      <el-form :model="formData">
        <el-form-item label="追溯码" :label-width="formLabelWidth">
          <el-input v-model="formData.cur_code" auto-complete="off" disabled></el-input>
        </el-form-item>
        <el-form-item label="生产日期" :label-width="formLabelWidth">
          <el-input v-bind:value="formData.batch.made_date | dateFormat" auto-complete="off" disabled></el-input>
        </el-form-item>
        <h3>药品信息</h3>
        <el-form-item label="药品通用名称" :label-width="formLabelWidth">
          <el-input v-model="formData.drug.common_name" auto-complete="off" disabled></el-input>
        </el-form-item>
        <el-form-item label="批准文号" :label-width="formLabelWidth">
          <el-input v-model="formData.drug.approval_number" auto-complete="off" disabled></el-input>
        </el-form-item>
        <el-form-item label="批准文号有效期" :label-width="formLabelWidth">
          <el-input v-model="formData.drug.approval_expiry_date" auto-complete="off" disabled></el-input>
        </el-form-item>
        <el-form-item label="药品有效期" :label-width="formLabelWidth">
          <el-input v-model="formData.drug.expiry_date_number" auto-complete="off" disabled></el-input>
        </el-form-item>
        <el-form-item label="有效期单位" :label-width="formLabelWidth">
          <el-input v-model="formData.drug.expiry_date_unit" auto-complete="off" disabled></el-input>
        </el-form-item>
        <el-form-item label="剂型" :label-width="formLabelWidth">
          <el-input v-model="formData.drug.form" auto-complete="off" disabled></el-input>
        </el-form-item>
        <el-form-item label="制剂规格" :label-width="formLabelWidth">
          <el-input v-model="formData.drug.standard" auto-complete="off" disabled></el-input>
        </el-form-item>
        <el-form-item label="生产企业" :label-width="formLabelWidth">
          <el-input v-model="formData.drug.factory" auto-complete="off" disabled></el-input>
        </el-form-item>
        <!-- <el-form-item label="所属企业" :label-width="formLabelWidth">
          <el-input v-model="formData.drug.enterprise" auto-complete="off" disabled></el-input>
        </el-form-item> -->
        <el-form-item label="包装规格" :label-width="formLabelWidth">
          <el-input v-model="formData.drug.package_spec" auto-complete="off" disabled></el-input>
        </el-form-item>
        <el-form-item label="包装比例" :label-width="formLabelWidth">
          <el-input v-model="formData.drug.packing_proportion" auto-complete="off" disabled></el-input>
        </el-form-item>
        <el-form-item label="商品名" :label-width="formLabelWidth">
          <el-input v-model="formData.drug.product_name" auto-complete="off" disabled></el-input>
        </el-form-item>
        <el-form-item label="年赋码量" :label-width="formLabelWidth">
          <el-input v-model="formData.drug.code_quantity" auto-complete="off" disabled></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <!-- <el-button @click="dialogFormVisibleShow = false">取 消</el-button> -->
        <el-button type="primary" @click="dialogFormVisibleShow = false">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="自定义列表" :visible.sync="setColumnsShow">
      <template>
        <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
        <div style="margin: 15px 0;"></div>
        <el-checkbox-group v-model="columns" @change="handleCheckedHeaderChange" class="tableSelect">
          <el-checkbox v-for="item in columnsSelect" :label="item" :key="item" border>{{item}}</el-checkbox>
        </el-checkbox-group>
        <div style="text-align:right">
          <el-button class="el-button--primary" @click="setLocalColumns">保存</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog title="位置信息" :visible.sync="medcodeLocationShow">
      <template>
        <div class="medcode-location" v-loading="stepsForm.loading" style="height:300px;padding:50px">
          <el-steps :active="activeSteps" direction="vertical">
            <el-step v-for="item in stepsForm.data" :key="item.title" :title="item.title" icon="iconfont icon-ti-factory" :description="item.description"></el-step>
          </el-steps>
        </div>
      </template>
    </el-dialog>
    <el-dialog title="关联关系" :visible.sync="dialogLinkShow">
      <h3>
        <label>当前追溯码:</label>
        <span style="color:#409EFF">{{linkHeader}}</span>
      </h3>
      <h3>
        <label>追溯码级别:</label>
        <span style="color:#409EFF">{{packLayer}}</span>
      </h3>
      <div v-if="this.packLayer <= 2 ">
        <el-table :data="linkData.data" v-loading="linkData.loading" class="table-common" border :max-height="linkTableHeight">
          <el-table-column type="index" label="#">
          </el-table-column>
          <el-table-column prop="cur_code" label="当前追溯码">
          </el-table-column>
          <el-table-column prop="pack_layer" label="包装级别" width="100">
          </el-table-column>
          <el-table-column label="关联关系" width="100">
            <template slot-scope="scope">
              <el-button v-if="scope.row.pack_layer != 3" @click="getLinkData(scope.row)" type="primary" disabled plain size="mini">上级码</el-button>
              <el-button v-else plain size="mini" type="primary" disabled>上级码</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="block" style="text-align:center">
          <el-pagination @size-change="linkHandleSizeChange" @current-change="linkHandleCurrentChange" :current-page="linkData.currentPage"
            :page-sizes="[20]" :page-size="linkData.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="linkData.dataSize">
          </el-pagination>
        </div>
      </div>
      <div v-else>
        <h3>
          <label>上级码:</label>
          <span style="color:#409EFF">无</span>
        </h3>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  const headerOptions = ['追溯码', '生产日期', '药品通用名称', '批准文号', '批准文号有效期', '药品有效期', '有效期单位', '制剂规格', '生产企业'];

  export default {
    data() {
      return {
        searchData: '',
        isSearch: false,
        adminId: '',
        adminToken: '',
        enterprise: '',
        dialogFormVisibleShow: false,
        dialogLinkShow: false,
        // dialogFormVisibleSubmit: false,
        medcodeLocationShow: false,
        activeSteps: 2,
        setColumnsShow: false,
        isIndeterminate: true,
        formLabelWidth: '150px',
        checkAll: false,
        tableHeight: '',
        linkTableHeight: '',
        cur_code: '',
        traceData: {
          data: [],
          loading: true,
          currentPage: 1,
          pageSize: 20,
          dataSize: 0,
        },
        linkHeader: '',
        packLayer: 3,
        linkData: {
          data: [],
          loading: true,
          currentPage: 1,
          pageSize: 20,
          dataSize: 0,
        },

        formData: {
          "cur_code": "",
          "created_at": "",
          "drug": {

          },
          'batch': {}
        },
        columns: [
          '追溯码',
          '药品通用名称',
          '批准文号',
          '制剂规格',
          '生产企业'
        ],
        columnsSelect: headerOptions,
        // submitForm:{}
        backSteps: [{
            title: '生产企业',
            description: '生产企业   2017-11-14    13:39:00 上海'
          },
          {
            title: '流通企业',
            description: '流通企业   2017-11-15   14:45:00 上海'
          },
          {
            title: '杭州中转站',
            description: '杭州中转站    2017-11-16 13:47:00 杭州'
          },
          {
            title: '零售企业',
            description: '零售企业'
          }
        ],
        stepsForm: {
          data: '',
          loading: 'true'
        }
      }
    },
    filters: {
      dateFormat: function (date) {
        if (date) {
          return date.slice(0, 11)
        } else {
          return false
        }

      }
    },
    methods: {
      getTraceData() {
        this.traceData.loading = true
        let curCode = ""
        if (this.isSearch) {
          curCode = this.searchData
        } else {
          curCode = ""
        }
        this.$http({
          url: '/batch-code/?' + 'page=' + this.traceData.currentPage + '&pack_layer=' + this.packLayer +
            '&cur_code=' + curCode,
          method: 'get',
          headers: {
            'Authorization': 'Token ' + this.adminToken
          },
        }).then(
          response => {
            console.log(response)
            if (response.data.count < 100) {
              this.traceData.dataSize = response.data.count
            } else {
              this.traceData.dataSize = 100
            }
            this.traceData.data = []
            this.traceData.data = response.data.results
            console.log(this.traceData.data)
            this.$message({
              type: 'success',
              message: '查询成功'
            })
            this.traceData.loading = false
            this.isSearch = false
          }
        ).catch(error => {
          console.log(error.response)
          if (error.response.status == 401) {
            this.$message({
              message: error.response.data.detail,
              type: 'warning'
            })
            this.$router.push({
              path: '/login'
            });
          } else if (error.response.status == 400) {
            this.$message({
              message: 'error400',
              type: 'error'
            })
          } else if (error.response.status == 404) {
            this.$message({
              message: error.response.data.detail,
              type: 'warning'
            })
          } else {
            this.$message({
              message: '未知错误',
              type: 'error'
            })
          }
          console.log(error);
        });
      },
      getLocationCode(code) {
        const self = this
        this.$http({
          url: '/batch-code/?cur_code=' + code,
          method: 'get',
          headers: {
            'Authorization': 'Token ' + this.adminToken
          },
        }).then(
          response => {
            console.warn(response)
            if (response.data.results[0].pack_layer != 3) {
              this.getLocationCode(response.data.results[0].parent_code)
            } else {
              let code = response.data.results[0].cur_code
              let made_date = response.data.results[0].batch.made_date
              this.$http({
                url: '/sales-out/?search=' + code,
                headers: {
                  'Authorization': 'Token ' + this.adminToken
                },
                method: 'get'
              }).then(
                response => {

                  //success
                  //   this.$message({
                  //   message: '警告哦，这是一条警告消息',
                  //   type: 'warning'
                  // });
                  //测试用
                  this.activeSteps = response.data.results.length + 1
                  this.stepsForm.data = []
                  this.stepsForm.data.push({
                    title: '生产企业',
                    description: "上海现代制药股份有限公司  -  " + response.data.results[0].act_date
                  })
                  if (response.data.results.length > 0) {
                    this.stepsForm.data.push({
                      title: '流通企业',
                      description: "上海现代制药营销有限公司"
                    })
                    console.log(this.activeSteps)
                  }
                  this.stepsForm.loading = false
                }
              ).catch(error => {
                console.log(error.response)
                if (error.response.status == 401) {
                  self.$message({
                    message: error.response.data.detail,
                    type: 'warning'
                  })
                  this.$router.push({
                    path: '/login'
                  });
                } else if (error.response.status == 400) {
                  this.$message({
                    message: 'error400',
                    type: 'error'
                  })
                } else if (error.response.status == 404) {
                  this.$message({
                    message: error.response.data.detail,
                    type: 'warning'
                  })
                } else {
                  this.$message({
                    message: '未知错误',
                    type: 'error'
                  })
                }
                console.log(error);
              });
            }
          }
        ).catch(error => {
          console.log(error.response)
          if (error.response.status == 401) {
            this.$message({
              message: error.response.data.detail,
              type: 'warning'
            })
            this.$router.push({
              path: '/login'
            });
          } else if (error.response.status == 400) {
            this.$message({
              message: 'error400',
              type: 'error'
            })
          } else if (error.response.status == 404) {
            this.$message({
              message: error.response.data.detail,
              type: 'warning'
            })
          } else {
            this.$message({
              message: '未知错误',
              type: 'error'
            })
          }
          console.log(error);
        });
      },
      getLinkData(row) {
        this.linkData.loading = true
        this.linkData.currentPage = 1
        this.linkData.curCode = row.parent_code
        this.packLayer = row.pack_layer
        this.linkHeader = row.cur_code
        this.$http({
          url: '/batch-code/?page=' + this.linkData.currentPage + '&cur_code=' + this.linkData.curCode,
          headers: {
            'Authorization': 'Token ' + this.adminToken
          },
          method: 'get'
        }).then(
          response => {
            //success
            //   this.$message({
            //   message: '警告哦，这是一条警告消息',
            //   type: 'warning'
            // });
            console.log(response.data)
            this.linkData.data = []
            this.linkData.data = response.data.results
            if (response.data.results[0].parent_code) {
              this.linkData.data.push({
                cur_code: response.data.results[0].parent_code,
                pack_layer: response.data.results[0].pack_layer + 1
              })
            }

            //最大页数
            if (response.data.count < 10000) {
              this.linkData.dataSize = response.data.count
            } else {
              this.linkData.dataSize = 10000
            }
            this.linkData.loading = false
          }
        ).catch(error => {
          console.log(error.response)
          if (error.response.status == 401) {
            this.$message({
              message: error.response.data.detail,
              type: 'warning'
            })
            this.$router.push({
              path: '/login'
            });
          } else if (error.response.status == 400) {
            this.$message({
              message: 'error400',
              type: 'error'
            })
          } else if (error.response.status == 404) {
            this.$message({
              message: error.response.data.detail,
              type: 'warning'
            })
          } else {
            this.$message({
              message: '未知错误',
              type: 'error'
            })
          }
          console.log(error);
        });
      },
      traceSearch() {
        this.packLayer = ''
        this.isSearch = true
        if (this.searchData != '') {
          this.traceData.currentPage = 1
          this.getTraceData()
        } else {
          this.$message({
            message: '请输入药品追溯码',
            type: 'warning'
          })
        }

      },
      handleClick(row) {
        this.dialogVisible = true
        console.log(row);
      },
      showForm(row) {
        console.log(row)
        this.dialogFormVisibleShow = true
        this.formData = row
      },
      setColumns: function () {
        this.setColumnsShow = true
        // this.columns.push('standard')
      },
      setLocalColumns: function () {
        this.setColumnsShow = false
        localStorage.setItem('CompanyCodeColumns', JSON.stringify({
          colums: this.columns
        }))
        this.$message({
          type: 'success',
          message: '保存成功'
        })
      },
      handleCheckAllChange(val) {
        this.columns = val ? headerOptions : [];
        this.isIndeterminate = false;
      },
      handleCheckedHeaderChange(value) {
        let checkedCount = value.length;
        this.checkAll = checkedCount === this.columnsSelect.length;
        this.isIndeterminate = checkedCount > 0 && checkedCount < this.columnsSelect.length;
        console.log(this.columns)
      },
      showLocation(row) {
        this.medcodeLocationShow = true
        this.stepsForm.loading = true
        this.getLocationCode(row.cur_code)

      },
      traceHandleSizeChange(val) {
        this.traceData.loading = true
        console.log(`每页 ${val} 条`);
      },
      traceHandleCurrentChange(val) {
        console.log(`当前页: ${val}`);
        this.traceData.currentPage = val
        if (this.isSearch) {

        } else {
          this.getTraceData()
        }

      },
      linkHandleSizeChange(val) {
        this.linkData.loading = true
        console.log(`每页 ${val} 条`);
      },
      linkHandleCurrentChange(val) {
        console.log(`当前页: ${val}`);
        this.linkData.currentPage = val
        this.getLinkData()
      },
      showLink(row) {
        this.dialogLinkShow = true
        this.linkData.currentPage = 1
        this.getLinkData(row)
      },
    },
    mounted() {
      this.adminId = this.$store.getters.getInfo.id
      this.adminToken = this.$store.getters.getInfo.token
      this.enterprise = this.$store.getters.getInfo.enterprise
      this.tableHeight = document.getElementsByClassName('table-common')[0].parentNode.clientHeight - 130
      this.linkTableHeight = 390

      if (localStorage.getItem('CompanyCodeColumns')) {
        this.columns = JSON.parse(localStorage.getItem('CompanyCodeColumns')).colums
      }
      this.getTraceData('')
    },
  }

</script>

<style scoped>
  #Company_medcode_search>>>.el-dialog {
    max-height: 600px;
    overflow: scroll;
  }

  .el-step {
    padding-bottom: 30px;
    max-width: 100% !important;
  }

  .navMid {
    width: 220px;
  }

  h3>label {
    display: inline-block;
    width: 100px;
  }

</style>
